package org.yinxue.example.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.yinxue.example.netty.core.codec.HeartBeatDecoder;
import org.yinxue.example.netty.core.codec.HeartBeatEncoder;
import org.yinxue.example.netty.server.handler.HeartBeatServerHandler;

/**
 * NettyServer {@link org.yinxue.example.netty.server}
 *
 * @author zengjian
 * @date 2019/1/1
 * @since 1.0.0
 */
public class NettyServer {

    private String host;
    private int port;

    public NettyServer(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new HeartBeatEncoder());
                        socketChannel.pipeline().addLast(new HeartBeatDecoder());
                        socketChannel.pipeline().addLast(new HeartBeatServerHandler());
                    }
                });
        ChannelFuture future = serverBootstrap.bind(host, port).addListener(future1 -> System.out.println("绑定端口ok: host:" + host + " port:" + port));
        future.channel().closeFuture().syncUninterruptibly();
    }

    public void stop(){
        // TODO
    }

}